import 'dart:collection';
import '../constants/api_constants.dart';

/// 请求频率限制器
/// 防止触发API的频率限制
class RateLimiter {
  final Duration _interval;
  final Queue<DateTime> _requestTimes = Queue<DateTime>();
  
  RateLimiter({Duration? interval}) 
    : _interval = interval ?? ApiConstants.rateLimitDelay;

  /// 等待下一个请求的时机
  Future<void> waitForNextRequest() async {
    final now = DateTime.now();
    
    // 清除超过时间窗口的旧请求记录
    _requestTimes.removeWhere((time) => 
      now.difference(time) > const Duration(seconds: 1));
    
    // 如果在1秒内已有3个请求，需要等待
    if (_requestTimes.length >= 3) {
      final oldestTime = _requestTimes.first;
      final waitTime = const Duration(seconds: 1) - now.difference(oldestTime);
      
      if (waitTime.inMilliseconds > 0) {
        await Future.delayed(waitTime);
      }
    }
    
    // 记录这次请求时间
    _requestTimes.add(DateTime.now());
  }
  
  /// 检查是否可以立即发送请求
  bool canMakeRequest() {
    final now = DateTime.now();
    
    // 清除超过时间窗口的旧请求记录
    _requestTimes.removeWhere((time) => 
      now.difference(time) > const Duration(seconds: 1));
    
    return _requestTimes.length < 3;
  }
  
  /// 获取距离下次可请求的等待时间
  Duration getWaitTime() {
    if (canMakeRequest()) {
      return Duration.zero;
    }
    
    final now = DateTime.now();
    final oldestTime = _requestTimes.first;
    final waitTime = const Duration(seconds: 1) - now.difference(oldestTime);
    
    return waitTime.isNegative ? Duration.zero : waitTime;
  }
  
  /// 重置限制器
  void reset() {
    _requestTimes.clear();
  }
  
  /// 获取当前请求队列状态
  Map<String, dynamic> getStatus() {
    final now = DateTime.now();
    
    // 清除过期记录
    _requestTimes.removeWhere((time) => 
      now.difference(time) > const Duration(seconds: 1));
    
    return {
      'requestsInLastSecond': _requestTimes.length,
      'maxRequestsPerSecond': 3,
      'canMakeRequest': canMakeRequest(),
      'nextAvailableTime': canMakeRequest() 
        ? now 
        : now.add(getWaitTime()),
    };
  }
} 